package me.kuye.jkuye.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.kuye.jkuye.log.Logger;
import me.kuye.jkuye.render.Render;
import me.kuye.jkuye.render.RenderFactory;
import me.kuye.jkuye.util.StringUtil;

public class ActionException extends RuntimeException {
	private static final Logger logger = Logger.getLogger(ActionException.class);
	private int errorCode;
	private Render errorRender;

	public ActionException(final int errorCode, final Render errorRender) {
		if (errorRender == null)
			throw new IllegalArgumentException("The parameter errorRender can not be null.");
		this.errorCode = errorCode;
		if (errorRender instanceof me.kuye.jkuye.render.ErrorRender) {
			this.errorRender = errorRender;
		} else {
			this.errorRender = new Render() {
				public Render setContext(HttpServletRequest req, HttpServletResponse res, String viewPath) {
					errorRender.setContext(req, res, viewPath);
					res.setStatus(errorCode);
					return this;
				}

				public void render() {
					errorRender.render();
				}
			};
		}
	}

	public ActionException(int errorCode, String errorView) {
		if (StringUtil.isEmpty(errorView))
			throw new IllegalArgumentException("The parameter errorView can not be blank.");

		this.errorCode = errorCode;
		this.errorRender = RenderFactory.getInstance().getErrorRender(errorCode, errorView);
	}

	public ActionException(int errorCode, Render errorRender, String errorMessage) {
		this(errorCode, errorRender);
		logger.warn(errorMessage);
	}

	public int getErrorCode() {
		return errorCode;
	}

	public Render getErrorRender() {
		return errorRender;
	}
}
